package javase.concurrency;

/**
 * 多线程
 * 
 * @Package javase
 * @ClassName: ThreadTest
 * @author Realfighter
 * @date 2014-7-8 下午01:32:01
 */
public class ThreadTest {

	public static void main(String[] args) {
		new ThreadByThread().start();
		new Thread(new ThreadByRunnable()).start();
	}

	/**
	 * synchronized确保互斥，去掉synchronized试试看?
	 * 
	 * @Title: testSynchronized
	 * @author Realfighter
	 * @date 2014-7-8 下午04:25:48
	 * @param name
	 * @param i
	 *            void
	 */
	public static synchronized void testSynchronized(String name, int i) {
		for (int j = 0; j < 10; j++) {
			System.out.println(name + " print >>>>>>" + i * j);
		}
	}

	public static volatile int count = 0;

	/**
	 * volatile确保数据同步
	 * 
	 * @Title: testVolatile
	 * @author Realfighter
	 * @date 2014-7-8 下午04:35:08
	 * @param name
	 * @param i
	 *            void
	 */
	public static void testVolatile(String name, int i) {
		for (int j = 0; j < 10; j++) {
			count++;
			System.out.println(count + " print >>>>>>" + i * j);
		}
	}

}

class ThreadByThread extends Thread {
	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			// ThreadTest.testSynchronized(Thread.currentThread().getName(), i);
			ThreadTest.testVolatile(Thread.currentThread().getName(), i);
		}
	}
}

class ThreadByRunnable implements Runnable {
	public void run() {
		for (int i = 0; i < 50; i++) {
			// ThreadTest.testSynchronized(Thread.currentThread().getName(), i);
			ThreadTest.testVolatile(Thread.currentThread().getName(), i);
		}
	}
}